package commons.base.task;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import commons.base.util.NamedThreadFactory;

public class ThreadPools {

	/**
	 * 创建一个有界任务队列线程池
	 * @param nThreads
	 * @param queueCapacity
	 * @param threadPoolPrefix
	 * @return
	 */
	public static ExecutorService newQueuedThreadPool(int nThreads, int queueCapacity, String threadPoolPrefix) {
		return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
				new LinkedBlockingQueue<Runnable>(queueCapacity), new NamedThreadFactory(threadPoolPrefix),
				new MyAbortPolicy());
	}
	
	/**
	 * 针对JDK自带的AbortPolicy做了两点优化：
	 * 1.去掉耗时的executor.toString()
	 * 2.重写耗时的fillInStackTrace方法
	 * @author yuan<cihang.yuan@happyelements.com>
	 *
	 */
	public static class MyAbortPolicy implements RejectedExecutionHandler{

		@Override
		public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
			throw new RejectedExecutionException("Task " + r.toString()){
				
				private static final long serialVersionUID = -8567800623334957566L;

				@Override
				public Throwable fillInStackTrace(){
					return this;
				}
			};
		}
		
	}
}
